package com.cebbank.yyi.springbootapp.jingtang.utils;

import cn.hutool.core.util.StrUtil;
import com.cebbank.yyi.springbootapp.jingtang.ResponseInfo;
import com.cebbank.yyi.springbootapp.jingtang.dto.ConditionParams;
import com.cebbank.yyi.springbootapp.jingtang.dto.DbMigrationParams;
import com.cebbank.yyi.springbootapp.jingtang.enums.DocType;
import com.cebbank.yyi.springbootapp.jingtang.json.MenuBO;
import lombok.extern.slf4j.Slf4j;
import okhttp3.*;

import java.io.File;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import java.util.Objects;

@Slf4j
public class RequestUtil {

    private final static String DOWNLOAD_URL_PREFIX = "http://wdgl.sgjtsteel.com:8081";

    public final static String ANNEX_FILE_PREFIX = "http://wdgl.sgjtsteel.com:8081/doc/fileInfo/getAnnexFileList/";

    private final static String URL_PREFIX = "http://wdgl.sgjtsteel.com:8081/doc/";

    // 开发
//     private final static String URL_SERVICE = "http://120.46.94.223:8080/";
    // 新开发
//     private final static String URL_SERVICE = "http://120.53.92.183:8080/";

    // 测试
//    private final static String URL_SERVICE = "http://10.188.26.108:8080/";
//    private final static String URL_SERVICE2 = "http://10.188.26.108/";

    // 生产
    private final static String URL_SERVICE = "http://10.188.16.113:8080/";
    private final static String URL_SERVICE2 = "http://10.188.16.113/";

    public static String toRequest(DbMigrationParams dbMigrationParams, MenuBO menuBO, ConditionParams conditionParams) throws Exception {
        Request request = combineRequest(dbMigrationParams, menuBO, conditionParams);
        try (Response responseBody = new OkHttpClient().newCall(request).execute()) {
            if (responseBody.isSuccessful()) {
                ResponseBody body = responseBody.body();
                if (Objects.nonNull(body)) {
                    return body.string();
                }
            }
            System.err.println("接口调用失败：" + responseBody);
        } catch (Exception e) {
            System.err.println("接口调用异常：" + e.getMessage());
            return "捕获到异常,请求失败";
        }
        return "请求失败";

    }

    public static String toRequestForRecord(DbMigrationParams dbMigrationParams, ConditionParams conditionParams) {
        Request request = combineRequestForRecord(dbMigrationParams, conditionParams);
        try (Response responseBody = new OkHttpClient().newCall(request).execute()) {
            if (responseBody.isSuccessful()) {
                ResponseBody body = responseBody.body();
                if (Objects.nonNull(body)) {
                    return body.string();
                }
            }
            System.err.println("接口调用失败：" + responseBody);
        } catch (Exception e) {
            System.err.println("接口调用异常：" + e.getMessage());
            return "捕获到异常,请求失败";
        }
        return "请求失败";

    }

    public static String toRequestForRecords(String rulesId, String token) {
        Request request = combineRequestForRecords(rulesId, token);
        try (Response responseBody = new OkHttpClient().newCall(request).execute()) {
            if (responseBody.isSuccessful()) {
                ResponseBody body = responseBody.body();
                if (Objects.nonNull(body)) {
                    return body.string();
                }
            }
            System.err.println("接口调用失败：" + responseBody);
        } catch (Exception e) {
            System.err.println("接口调用异常：" + e.getMessage());
            return "捕获到异常,请求失败";
        }
        return "请求失败";

    }

    private static Request combineRequest(DbMigrationParams dbMigrationParams, MenuBO menuBO, ConditionParams conditionParams) {

        String url = buildUrl(dbMigrationParams, menuBO, conditionParams.getPageNo(), conditionParams.getPageSize());
        Map<String, String> headers = buildHeaders(dbMigrationParams.getToken());
        Request.Builder builder = new Request.Builder().get().url(url);
        headers.forEach(builder::addHeader);
        return builder.build();
    }

    private static Request combineRequestForRecord(DbMigrationParams dbMigrationParams, ConditionParams conditionParams) {

        String url = buildUrlForRecords(conditionParams.getPageNo(), conditionParams.getPageSize(), dbMigrationParams.getStatus());
        Map<String, String> headers = buildHeaders(dbMigrationParams.getToken());
        Request.Builder builder = new Request.Builder().get().url(url);
        headers.forEach(builder::addHeader);
        return builder.build();
    }


    private static Request combineRequestForRecords(String rulesId, String token) {

        String url = buildUrlForRecords(rulesId);
        Map<String, String> headers = buildHeaders(token);
        Request.Builder builder = new Request.Builder().get().url(url);
        headers.forEach(builder::addHeader);
        return builder.build();
    }

    private static Map<String, String> buildHeaders(String token) {
        Map<String, String> headers = new HashMap<>();
        headers.put("Authorization", "Bearer " + token);
        headers.put("Accept", "text/html,application/xhtml+xml,application/xml;q=0.9,image/avif,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3;q=0.7");
        headers.put("TENANT-ID", "1");
        headers.put("Connection", "keep-alive");
        headers.put("If-None-Match", "66155990-804d");
        headers.put("Upgrade-Insecure-Requests", "1");
        headers.put("Referer", "http://wdgl.sgjtsteel.com:8081/");
        headers.put("Origin", "http://wdgl.sgjtsteel.com:8081");
        headers.put("User-Agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/127.0.0.0 Safari/537.36 Edg/127.0.0.0");
        return headers;
    }

    private static String buildUrl(DbMigrationParams dbMigrationParams, MenuBO menuBO, int pageNum, int pageSize) {
        String url = String.join("", URL_PREFIX, Objects.requireNonNull(DocType.fromDesc(menuBO.getType())).getName());
        String urlParams = String.format("?current=%s&size=%s&menuType=%s&status=%s&fileName=&fileCate=&fileType=&formulateDepartmentId=&preparedBy=&effectDateStar=&effectDateEnd=&defaultStatus=3&searchDictCode=search_data_status&cutoffDateStar=&cutoffDateEnd=&rulesNo=&professionPropertyId=", pageNum, pageSize, menuBO.getMenuType(), dbMigrationParams.getStatus());
        return url + urlParams;
    }

    private static String buildUrlForRecords(int pageNum, int pageSize, String status) {
        return String.format("http://wdgl.sgjtsteel.com:8081/doc/dockfilerecords/page?menuType=8&current=%s&size=%s&status=%s&fileName=&fileCate=&fileType=&formulateDepartmentId=&simulationDraft=&effectDateStar=&effectDateEnd=&admin=&cutoffDateStar=&cutoffDateEnd=&rulesNo=&docType=&suggOrQuestion=&preparedBy=&defaultStatus=3&searchDictCode=search_data_status", pageNum, pageSize, status);
    }

    private static String buildUrlForRecords(String rulesId) {
        return String.format("http://wdgl.sgjtsteel.com:8081/doc/dockfilerecords/listBasis?rulesId=%s", rulesId);
    }


    public static ResponseInfo downloadFile(String urlPath, String token) throws Exception {
        ResponseInfo responseInfo = new ResponseInfo();
        String url = DOWNLOAD_URL_PREFIX + urlPath;
        Map<String, String> headers = buildHeaders(token);
        Request.Builder builder = new Request.Builder().get().url(url);
        headers.forEach(builder::addHeader);
        Request request = builder.build();
        OkHttpClient okHttpClient = new OkHttpClient();
        Response response = okHttpClient.newCall(request).execute();
        String disPosed = response.headers().get("Content-Disposition");
        String originalFileName = "";
        if (disPosed != null) {
            originalFileName = disPosed.split("filename=")[1];
        }

        ResponseBody responseBody = response.body();
        if (null == responseBody) {
            throw new Exception("响应数据有误，响应数据无返回");
        }
        responseInfo.setResponseBody(responseBody);
        responseInfo.setOriginalFileName(originalFileName);
        return responseInfo;
    }

    public static ResponseBody getAnnexFileList(String fileId, String token) throws Exception {
        String url = ANNEX_FILE_PREFIX + fileId;
        Map<String, String> headers = buildHeaders(token);
        Request.Builder builder = new Request.Builder().get().url(url);
        headers.forEach(builder::addHeader);
        Request request = builder.build();
        OkHttpClient okHttpClient = new OkHttpClient();
        Response response = okHttpClient.newCall(request).execute();
        ResponseBody responseBody = response.body();
        if (null == responseBody) {
            throw new Exception("响应数据有误，响应数据无返回");
        }
        return responseBody;
    }

    /**
     * 主文件上传
     *
     * @param path
     * @return
     */
    public static String uploadMainFile(String path, String docId, String directoryType) {
        String url = URL_SERVICE + "prod-api/api/v1/doc_manager/uploadDocFile";
        File file = new File(path);
        if (!file.exists()) {
            System.err.println("本地文件不存在：" + path);
        }
        String responseStr = null;

        OkHttpClient okHttpClient = new OkHttpClient();
        RequestBody requestBody = buildFormData(file, docId, directoryType);
        Request request = new Request.Builder().url(url).post(requestBody).build();
        try (Response response = okHttpClient.newCall(request).execute()) {
            if (null == response.body()) {
                System.err.println("主文件上传失败，服务端未响应");
            } else {
                responseStr = response.body().string();
                response.body().close();
                response.close();
            }
        } catch (Exception e) {
            System.err.println("主文件上传失败：" + e.getMessage());
        }
        return responseStr;
    }

    public static String syncEs(String docId) {
        String resquestUrl = URL_SERVICE + "prod-api/api/v1/doc_manager/docSave?docId=%s";
        // 创建 OkHttpClient 实例
        OkHttpClient client = new OkHttpClient();
        Map<String, String> headers = new HashMap<>();
        headers.put("userid", "1797526856446169090");
        // 构建请求
        Request.Builder url = new Request.Builder().url(String.format(resquestUrl, docId));
        headers.forEach(url::addHeader);
        Request request = url.build();
        // 发送请求并获取响应
        try (Response response = client.newCall(request).execute()) {
            if (response.isSuccessful()) {
                // 打印响应体
                ResponseBody body = response.body();
                if (body != null) {
                    String bodys = body.string();
                    body.close();
                    log.info("syncEs结果响应码:{}", response.code());
                    return bodys;
                }
            } else {
                System.err.println("syncEs请求失败: " + response.code());
                log.error("syncEs请求失败:{}", docId);
            }
        } catch (IOException e) {
            System.err.println("syncEs失败: " + e.getMessage());
        }
        return "syncEs失败";
    }


    public static String getEsDocById(String docId) throws IOException {
        String requestUrl = URL_SERVICE + "prod-api/api/v1/doc_manager/getEsDocById?docId=%s";
        // 创建 OkHttpClient 实例
        OkHttpClient client = new OkHttpClient();
        // 构建请求
        Request request = new Request.Builder().url(String.format(requestUrl, docId)).build();
        // 发送请求并获取响应
        try (Response response = client.newCall(request).execute()) {
            if (response.isSuccessful()) {
                // 打印响应体
                ResponseBody body = response.body();
                if (body != null) {
                    String bodys = body.string();
                    body.close();
//                    System.err.println("getEsDocById响应码:" + response.code());
                    return bodys;
                }
            } else {
                System.out.println("getEsDocById请求失败: " + response.code());
            }
        } catch (IOException e) {
            System.err.println("getEsDocById失败:" + e.getMessage());
        }
        return "getEsDocById失败";
    }

    public static String deleteEsById(String esId) throws IOException {
        String requestUrl = URL_SERVICE + "prod-api/api/v1/doc_manager/deleteEsById?id=%s";
        // 创建 OkHttpClient 实例
        OkHttpClient client = new OkHttpClient();
        // 构建请求
        Request request = new Request.Builder().url(String.format(requestUrl, esId)).build();
        // 发送请求并获取响应
        try (Response response = client.newCall(request).execute()) {
            if (response.isSuccessful()) {
                // 打印响应体
                ResponseBody body = response.body();
                if (body != null) {
                    String bodys = body.string();
                    body.close();
                    System.err.println("deleteEsById响应码:" + response.code());
                    return bodys;
                }
            } else {
                System.err.println("deleteEsById请求失败: " + response.code());
            }
        } catch (IOException e) {
            System.err.println("deleteEsById失败:" + e.getMessage());
        }
        return "deleteEsById失败";
    }


    private static RequestBody buildFormData(File file, String docId, String directoryType) {
        MediaType mediaType = MediaType.parse("text/plain");
        String name = file.getName();
//        name = name.replaceAll("#", "_").replaceAll("\\+", "_").replaceAll(" ", "_").replaceAll(",", "_").replaceAll("%", "_");
        System.err.printf("开始构建[%s]的formData\n", name);
        MultipartBody.Builder builder = new MultipartBody.Builder().setType(MultipartBody.FORM).addFormDataPart("file", name, RequestBody.create(mediaType, file));
        if (StrUtil.isNotEmpty(docId)) {
            builder.addFormDataPart("docId", docId);
        }
        if (StrUtil.isNotEmpty(directoryType)) {
            builder.addFormDataPart("directoryType", directoryType);
        }
        return builder.build();
    }

    public static String uploadAttachmentFile(String path, String docId) {
        String url = URL_SERVICE + "prod-api/api/v1/doc_manager/uploadDocAttachmentFile/" + docId;
        File file = new File(path);
        if (!file.exists()) {
            System.err.println("本地文件不存在：" + path);
        }
        String responseStr = null;

        OkHttpClient okHttpClient = new OkHttpClient();
        RequestBody requestBody = buildFormData(file, null, null);
        Request request = new Request.Builder().url(url).post(requestBody).build();
        try {
            Response response = okHttpClient.newCall(request).execute();
            if (null == response.body()) {
                System.err.println("附件文件上传失败，服务端未响应");
            } else {
                responseStr = response.body().string();
                response.body().close();
                response.close();
            }
        } catch (Exception e) {
            System.err.println("附件文件上传失败：" + e.getMessage());
        }
        return responseStr;
    }

    public static String uploadAttachmentFile2(String path, String docId) {
        String url = URL_SERVICE2 + "prod-api/api/v1/doc_manager/uploadDocAttachmentFile2/" + docId;
        File file = new File(path);
        if (!file.exists()) {
            System.err.println("本地文件不存在：" + path);
        }
        String responseStr = null;

        OkHttpClient okHttpClient = new OkHttpClient();
        RequestBody requestBody = buildFormData(file, null, null);
        Request request = new Request.Builder().url(url).post(requestBody).build();
        try {
            Response response = okHttpClient.newCall(request).execute();
            if (null == response.body()) {
                System.err.println("附件文件上传失败，服务端未响应");
            } else {
                responseStr = response.body().string();
                response.body().close();
                response.close();
            }
        } catch (Exception e) {
            System.err.println("附件文件上传失败：" + e.getMessage());
        }
        return responseStr;
    }

    public static String docEsSync(String docId) {
        String url = URL_SERVICE + "/prod-api/api/v1/doc_manager/uploadDocAttachmentFile2/" + docId;
        OkHttpClient okHttpClient = new OkHttpClient();
        Request request = new Request.Builder().url(url).get().build();
        String responseStr = null;
        try {
            Response response = okHttpClient.newCall(request).execute();
            if (null == response.body()) {
                System.err.println("ES同步失败，服务端未响应");
            } else {
                responseStr = response.body().string();
                response.body().close();
                response.close();
            }
        } catch (Exception e) {
            System.err.println("ES同步失败：" + e.getMessage());
        }
        return responseStr;
    }


    /***
     * {
     *   "code": 0,
     *   "msg": null,
     *   "data": {
     *       "paperworkOpinion": null,
     *       "lastOpinion": "建议同意 制造部 郭亮 2023-12-07 11:08:44",
     *       "reviewerOpinion": "同意。 公司领导 周建 2023-12-12 12:08:37, 办公室(三办、机关党委办公室) 卢婷 2023-12-25 10:45:58,同意 公司领导 李明 2023-12-29 10:04:22"
     *   }
     * }
     *
     *
     *
     * **/
    //请求文件审批结果
    public static String getApprovalRecord(String oldDocId, String token) {
        String requestUrl = URL_PREFIX + "/work/getCompanyNodeInfo?id=%s";
        OkHttpClient client = new OkHttpClient();
        // 构建请求
        Map<String, String> headers = buildHeaders(token);
        Request.Builder builder = new Request.Builder().url(String.format(requestUrl, oldDocId));
        headers.forEach(builder::addHeader);
        Request request = builder.build();
        // 发送请求并获取响应
        try (Response response = client.newCall(request).execute()) {
            if (response.isSuccessful()) {
                // 打印响应体
                ResponseBody body = response.body();
                if (body != null) {
                    String bodys = body.string();
                    body.close();
                    log.info("syncEs结果响应码:{}", response.code());
                    return bodys;
                }
            } else {
                System.err.println("syncEs请求失败: " + response.code());
            }
        } catch (IOException e) {
            System.err.println("syncEs失败: " + e.getMessage());
        }
        return "获取结果失败";
    }


}


